<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\facade\Session;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;

use app\admin\validate\UsersValidate;

use app\admin\model\{Admin, Cate, Users, TechnGoods, TechnCate, Goods, TechnFiles};

class TechnController extends BaseController
{
    private $userModel;
    private $token;
    public function __construct(Users $userModel)
    {
        $this->userModel = $userModel;
        $this->token = Session::get('token');
    }

    // 渲染员工列表页面
    public function techn_list()
    {   
        $adminModel = new Admin();

        if($this->token['role_id'] < 2){
            $where = [['role_id', '=', 2]];
        }else{
            $where = ['id' => $this->token['id']];
        }

        $admin_list = $adminModel->getList($where, 0);

        if($admin_list['code'] != 'ok'){
            $admin_list['data'] = [];
        }

        View::assign('admin_list', $admin_list['data']);
        return view();
    }

    // 渲染员工编辑页面
    public function techn_edit()
    {   
        $data = input('get.');
        $adminModel = new Admin();
        $usersModel = new Users();
        $cateModel = new Cate();
        $goodsModel = new Goods();
        $technGoodsModel = new TechnGoods();
        $technCateModel = new TechnCate();
        $technFilesModel = new TechnFiles();

        // 获取员工信息
        $usersInfo = $usersModel->getFind(['id' => $data['id']])['data'];

        // 获取店铺列表
        $adminList = $adminModel->getList([['id', '<>', $usersInfo->getData('admin_id')], ['role_id', '=', 2]], 0);

        // 获取员工标签
        $technCateList = $cateModel->getList(['type' => 3], 0);

        // 获取员工技能
        $usersInfo['cate_ids'] = $technCateModel->getCol(['user_id' => $usersInfo['id']], 'cate_id')['data'];

        // 全部可选擅长项目
        $goodsList = $goodsModel->getList([['del_time', '=', 0], ['type', '=', 3], ['admin_id', '=', $usersInfo->getData('admin_id')]], 0, 0, 0, 'id, title');

        /** 已选擅长项目 */
        $goodsCheckList = $technGoodsModel->getCol(['user_id' => $data['id']], 'goods_id');

        /** 优秀作品图片 */
        $img_list = $technFilesModel->getList(['user_id' => $data['id']], 0);

        if($img_list['code'] != 'ok'){
            $img_list['data'] = [];
        }

        View::assign('techn', $usersInfo);
        View::assign('shop_list', $adminList['data']);
        View::assign('cate_list', $technCateList['data']);
        View::assign('goods_list', $goodsList['data']);
        View::assign('check_goods', $goodsCheckList['data']);
        View::assign('imgs', $img_list['data']);
        return view();
    }

    // 获取员工列表数据
    public function techn_data()
    {
        $data = input('get.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['type', '=', 2];
        $where[] = ['del_time', '=', 0];

        if($this->token['role_id'] == 1){
            $adminModel = new Admin();
            $admin_list = $adminModel->getList(['pid' => $this->token['id']], 'id');

            if($admin_list['code'] == 'ok'){
                $ids = array_column($admin_list['data']->toArray(), 'id');

                $where[] = ['admin_id', 'in', $ids];
            }
        }else if($this->token['role_id'] == 2){
            $where[] = ['admin_id', '=', $this->token['id']];
        }

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }

            if(!empty($data['key']['admin_id'])){
                $where[] = ['admin_id', '=', $data['key']['admin_id']];
            }
        }

        $technCateModel = new TechnCate();

        $count = $this->userModel->getNum($where)['data'];

        $field = 'id, nickname, head_img, phone, admin_id';
        $list = $this->userModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            $technCateLists = $technCateModel->getList(['user_id' => $v['id']], 0)['data'];
            $technCateLists = $technCateLists->toArray();
            $name = array_column($technCateLists, 'cate_id');
            $list['data'][$k]['cate'] = implode(' ', $name);
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 员工信息修改
    public function setTechnEdit()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $img = json_decode($data['img'], true);
        
        $flag = $this->userModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $technGoodsModel = new TechnGoods();
        $technCateModel = new TechnCate();
        $technFilesModel = new TechnFiles();

        /** 技能标签 */
        $techCateArr = [];
        $ids = explode(',', $data['cate_id']);
        array_pop($ids);

        foreach($ids as $k => $v){
            $techCateInfo = [
                'user_id' => $data['id'],
                'cate_id' => $v,
            ];

            $techCateArr[] = $techCateInfo;
        }

        $technCateModel->del(['user_id' => $data['id']]);
        $technCateModel->addAll($techCateArr);

        /** 擅长项目 */
        $goodsArr = [];
        $goods_ids = explode(',', $data['goods_id']);
        array_pop($goods_ids);

        foreach($goods_ids as $k => $v){
            $goodsInfo = [
                'user_id' => $data['id'],
                'goods_id' => $v,
            ];

            $goodsArr[] = $goodsInfo;
        }

        $technGoodsModel->del(['user_id' => $data['id']]);
        $technGoodsModel->addAll($goodsArr);

        /** 优秀作品 */
        $img_arr = [];
        foreach($img as $val){
            $img_info = [
                'file'     => $val['url'],
                'user_id'  => $data['id'],
            ];
            
            $img_arr[] = $img_info;
        }

        $technFilesModel->del(['user_id' => $data['id']]);

        /** 添加图片 */
        $technFilesModel->addAll($img_arr);

        $this->success_back('修改成功');
    }

    // 删除员工
    public function technDel()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $this->userModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }

    /** 图片上传 */
    public function imgUpMany(){
        $file = request()->file('file');

        $imgUrl = fileUp($file, 'techn');
        $this->success_back('ok', $imgUrl);
    }

    /** 图片删除 */
    public function del_img(){
        $id = input("post.id");

        $imgModel = new TechnFiles();
        $res = $imgModel->where("id", $id)->delete();

        if(!$res){
            $this->error_back('删除失败');
        }else{
            $this->success_back('删除成功');
        }
    }
}
